package com.xzr.demo.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xzr.demo.common.ConsumerEnv;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 存储消息的队列
 * MSG = Message
 *
 * @Author：徐志荣
 * @Date：2023/8/3 下午 4:42
 */

@Data
public class MSGQueue {
    //表示队列的身份标识
    private String name;
    //表示队列是否要持久化
    private boolean durable = false;
    //这个属性 true：一个消费者使用；false：大家都可以用；独占没有实现
    private boolean exclusive = false;
    //true: 没消费者使用，就自动删除；自动删除不实现
    private boolean autoDelete = false;
    //扩展参数，不实现
    private Map<String, Object> arguments = new HashMap<>();
    //当前队列都有哪些消费者订阅了
    private List<ConsumerEnv> consumerEnvList = new ArrayList<>();
    //记录当前取到了第几个消费者，方便轮询
    private AtomicInteger consumerSeq = new AtomicInteger();

    //添加一个新的订阅者
    public void addConsumerEnv(ConsumerEnv consumerEnv) {

        consumerEnvList.add(consumerEnv);

    }
    //订阅者的删除暂时先不考虑

    //挑选一个订阅者，用来处理当前的消息（按照轮询的方式）
    public ConsumerEnv chooseConsumer() {
        if (consumerEnvList.size() == 0) {
            //队列无人订阅
            return null;
        }
        //计算一下当前要取的元素的下标
        int index = consumerSeq.get() % consumerEnvList.size();
        consumerSeq.getAndDecrement();
        return consumerEnvList.get(index);
    }

    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    public void setArguments(String argumentsJson) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(argumentsJson, new TypeReference<Map<String, Object>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }


    public Object getArguments(String key) {
        return arguments.get(key);
    }

    public void setArguments(String key, Object value) {
        arguments.put(key, value);

    }

    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }


}
